<template>
  <div>
    <div class="gva-search-box">
      <p>节点名称：{{nodeName}}</p>
    </div>
    <div class="gva-search-box">
      <el-table
          :data="tableData"
          @sort-change="sortChange"
          @selection-change="handleSelectionChange"
      >
        <el-table-column
            align="left"
            label="服务器IP"
            min-width="150"
            prop="serverIP"
            sortable="custom"
        />
<!--        <el-table-column-->
<!--            align="left"-->
<!--            label="所属节点"-->
<!--            min-width="150"-->
<!--            prop="affiliatedNode"-->
<!--            sortable="custom"-->
<!--        />-->
        <el-table-column
            align="left"
            label="CPU使用率"
            min-width="150"
            prop="cpuUsage"
            sortable="custom"
        >
          <template #default="scope">
            {{ formatPercentage(scope.row.cpuUsage) }}
          </template>
        </el-table-column>
        <el-table-column
            align="left"
            label="内存使用率"
            min-width="150"
            prop="memoryUsage"
            sortable="custom"
        >
          <template #default="scope">
            {{ formatPercentage(scope.row.memoryUsage) }}
          </template>
        </el-table-column>
        <el-table-column
            align="left"
            label="磁盘使用率"
            min-width="150"
            prop="diskUsage"
            sortable="custom"
        >
          <template #default="scope">
            {{ formatPercentage(scope.row.diskUsage) }}
          </template>
        </el-table-column>
        <el-table-column
            align="left"
            fixed="right"
            label="进程"
            width="200"
        >
          <template #default="scope">
            <el-button
                :icon="scope.row.cpuUsage < 0 ? 'close' : 'edit'"
                :type="scope.row.cpuUsage < 0 ? 'default' : 'primary'"
                :disabled="scope.row.cpuUsage < 0"
                link
                @click="showProcessDetail(scope.row)"
            >
              {{ scope.row.cpuUsage < 0 ? '未运行' : '详情' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="gva-pagination">
        <el-pagination
            :current-page="page"
            :page-size="pageSize"
            :page-sizes="[10, 30, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
        />
      </div>
    </div>

    <el-drawer
        title="进程详情"
        v-model="processDetailVisible"
        size="80%"
        direction="rtl"
    >
      <el-table :data="currentProcessList">
        <el-table-column
            prop="ProcessNane"
            label="进程名称"
            min-width="150"
        />
        <el-table-column
            prop="CPU"
            label="CPU使用率"
            min-width="100"
        >
          <template #default="scope">
            {{ formatPercentage(scope.row.CPU) }}
          </template>
        </el-table-column>
        <el-table-column
            prop="Memory"
            label="内存占用"
            min-width="100"
        >
          <template #default="scope">
            {{ formatMemory(scope.row.Memory) }} %
          </template>
        </el-table-column>
        <el-table-column
            prop="MemoryUsed"
            label="内存使用量"
            min-width="150"
        >
          <template #default="scope">
            {{ formatMemory(scope.row.MemoryUsed) }} MB
          </template>
        </el-table-column>
        <el-table-column
            prop="ThreadNum"
            label="线程数"
            min-width="100"
        >
          <template #default="scope">
            {{ formatThreadNum(scope.row.ThreadNum) }}
          </template>
        </el-table-column>
        <el-table-column
            prop="Status"
            label="状态"
            min-width="100"
        />
        <el-table-column
            prop="CreateTime"
            label="创建时间"
            min-width="150"
        >
          <template #default="scope">
            {{ formatDate(scope.row.CreateTime) }}
          </template>
        </el-table-column>
      </el-table>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getNodeMonitor } from '@/api/node'

const route = useRoute()

const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const tableData = ref([])
const nodeID = ref('')
const nodeName = route.query.NodeName
const processDetailVisible = ref(false)
const currentProcessList = ref([])

const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}

const handleCurrentChange = (val) => {
  page.value = val
  getTableData()
}

const sortChange = ({ prop, order }) => {
  if (prop) {
    searchInfo.value.orderKey = prop
    searchInfo.value.desc = order === 'descending'
  }
  getTableData()
}

const handleSelectionChange = (val) => {
  // 处理选择变化逻辑
}

const getTableData = async () => {
  try {
    nodeID.value = route.query.nodeId || ''
    if (nodeID.value) {
      const response = await getNodeMonitor(page.value, pageSize.value, nodeID.value)
      if (response.code === 0) {
        tableData.value = response.data.ServerInfoList.map(server => ({
          serverIP: server.ServerIp,
          cpuUsage: server.CPU,
          memoryUsage: server.Memery,
          diskUsage: server.Disk,
          processList: server.ProcessList,
          affiliatedNode: response.data.NodeId
        }))
        total.value = tableData.value.length
      } else {
        ElMessage.error('数据加载失败')
      }
    } else {
      ElMessage.error('未找到 NodeId')
    }
  } catch (error) {
    ElMessage.error('数据加载失败')
  }
}

const showProcessDetail = (row) => {
  if (row.cpuUsage >= 0) {
    currentProcessList.value = row.processList
    processDetailVisible.value = true
  }
}

const formatPercentage = (value) => {
  const numericValue = parseFloat(value);
  if (!isNaN(numericValue)) {
    return `${Math.max(numericValue, 0).toFixed(4)}%`;
  }
  return value;
};

const formatMemory = (value) => {
  const numericValue = parseFloat(value);
  if (!isNaN(numericValue)) {
    return Math.max(numericValue, 0).toFixed(2);
  }
  return value;
};

const formatThreadNum = (value) => {
  const numericValue = parseInt(value, 10);
  if (!isNaN(numericValue)) {
    return Math.max(numericValue, 0);
  }
  return value;
};

const formatDate = (timestamp) => {
  const date = new Date(timestamp * 1000)
  return date.toLocaleString()
}

onMounted(() => {
  getTableData()
})

</script>

<style scoped lang="scss">
.warning {
  color: #dc143c;
}
</style>
